package com.dy.springcloud.controller;

import com.dy.springcloud.entity.Member;
import com.dy.springcloud.entity.Result;
import com.dy.springcloud.service.MemberOpenFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
//MemberConsumerController可以访问 member-service 微服务
public class MemberConsumerController {

    //使用在nacos中注册的服务名,必须小写
    private static final String MEMBER_SERVICE_NACOS_PROVIDER_URL = "http://member-service-nacos-provider";

    @Resource
    private RestTemplate restTemplate;

    //使用openfeign方式进行远程调用
    @Resource
    private MemberOpenFeignService memberOpenFeignService;


    @GetMapping("/member/nacos/consumer/get/{id}")
    public Result getMemberById(@PathVariable("id") Long id) {
        log.info("getMemberById"+id);
        //restTemplate使用get方法访问微服务                                                         返回类型
        return restTemplate.getForObject(MEMBER_SERVICE_NACOS_PROVIDER_URL + "/member/get/" + id, Result.class);
    }

    //使用openfeign方式进行远程调用
    @GetMapping("/member/Openfeign/nacos/consumer/get/{id}")
    public Result getMemberByIdOpenfeign(@PathVariable("id") Long id) {
        log.info("调用方式为Openfeign");
        //restTemplate使用get方法访问微服务                                                         返回类型
        return memberOpenFeignService.getMemberById(id);
    }

    @PostMapping("/member/nacos/consumer/save")
    public Result save(Member member) {
        log.info("member-consumer member: {}", member);
        //MEMBER_SERVICE_PROVIDER_URL + "/member/save"为微服务的接口方法url
        //member是发送的数据，restTemplate底层发送的是json格式，
        //所以微服务的方法的member参数需要 @RequestBody ，否则为null
        //restTemplate发送参数使用对象流，所以member需要implements Serializable
        return restTemplate.postForObject(MEMBER_SERVICE_NACOS_PROVIDER_URL + "/member/save", member, Result.class);
    }

}
